package com.example.music

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.TextView
import java.io.IOException

class MusicService : Service() {
    val Channel_ID="my channel"
    val Notification_ID=1
    companion object{
        val Commond="Operate"
    }
    val mediaPlayer= MediaPlayer()
    val musicList:MutableList<String> = mutableListOf<String>()
    val musicNameList:MutableList<String> = mutableListOf<String>()
    var current=0
    var isPause=false
    val binder=MusicBinder()
    inner class MusicBinder: Binder(){
        val  musicName:String
            get()= musicList.get(current)
        var currentPosition:Int
            get()=mediaPlayer.currentPosition
            set(value:Int)=mediaPlayer.seekTo(value)
        val duration:Int
            get()=mediaPlayer.duration
        val size:Int
            get()=musicList.size
        val currentIndex:Int
            get()=current
    }
    override fun onCreate() {
        super.onCreate()
        getMusicList()
        mediaPlayer.setOnPreparedListener{
            it.start()
        }
        mediaPlayer.setOnCompletionListener {
            current++
            if(current>=musicList.size){
                current=0
            }
            play()
        }
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate:Int = intent?.getIntExtra(Commond,1)?:1
        when(operate){
            1->Play()
            2->Pause()
            3->Stop()
            4->Next()
            5->Prev()
        }
        return super.onStartCommand(intent, flags, startId)
    }
    fun not(){
        val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder:Notification.Builder
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
            val notificationChannel= NotificationChannel(Channel_ID,"test", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(notificationChannel)
            builder=Notification.Builder(this,Channel_ID)
        }else{
            builder=Notification.Builder(this)
        }
        val intent=Intent(this,MainActivity::class.java)
        val pendingIntent= PendingIntent.getActivity(this,1,intent, PendingIntent.FLAG_IMMUTABLE)
        val notification: Notification =builder.setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle("2022110503")
            .setContentText("${binder!!.musicName}")
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()
        notificationManager.notify(Notification_ID,notification)
    }
    fun Play(){
        play()
    }
    fun Pause(){
        if(isPause){
            mediaPlayer.start()
            isPause = false
        }else{
            mediaPlayer.pause()
            isPause = true
        }
    }
    fun Stop(){
        mediaPlayer.stop()
        stopSelf()
    }
    fun Next(){
        current++
        if(current>=musicList.size){
            current=0
        }
        play()
    }
    fun Prev(){
        current--
        if(current>=musicList.size){
            current=musicList.size-1
        }
        play()
    }
    fun play(){
        if(musicList.size==0) return
        val path:String = musicList[current]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()

        }catch (e: IOException){
            e.printStackTrace()
        }
        not()
    }
    override fun onBind(intent: Intent): IBinder {
        return binder
    }
    private fun getMusicList(){
        val cursor: Cursor? = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,null)
        if(cursor!=null){
            while(cursor.moveToNext()){
                val musicPath:String = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
                musicList.add(musicPath)
                val musicName:String = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE))
                musicNameList.add(musicName)
                Log.d("MusicService","get:$musicPath name: $musicName")
            }
            cursor.close()
        }
    }
}